package controllers

import (
	"admin-glm-go/internal/models"
	"admin-glm-go/internal/response"
	"admin-glm-go/internal/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// ArticleListRequest 文章列表请求参数
type ArticleListRequest struct {
	Page       int    `form:"page"`
	PageSize   int    `form:"pageSize"`
	Title      string `form:"title"`
	CategoryID uint64 `form:"categoryId"`
	Status     int    `form:"status"`
}

// AddArticleRequest 添加文章请求参数
type AddArticleRequest struct {
	Title      string `json:"title" binding:"required"`
	CategoryID uint64 `json:"categoryId" binding:"required"`
	Image      string `json:"image"`
	Content    string `json:"content" binding:"required"`
	Summary    string `json:"summary"`
	Author     string `json:"author"`
	Source     string `json:"source"`
	Sort       int    `json:"sort"`
	Status     int    `json:"status"`
}

// UpdateArticleRequest 更新文章请求参数
type UpdateArticleRequest struct {
	ID         uint64 `json:"id" binding:"required"`
	Title      string `json:"title" binding:"required"`
	CategoryID uint64 `json:"categoryId" binding:"required"`
	Image      string `json:"image"`
	Content    string `json:"content" binding:"required"`
	Summary    string `json:"summary"`
	Author     string `json:"author"`
	Source     string `json:"source"`
	Sort       int    `json:"sort"`
	Status     int    `json:"status"`
}

// ArticleController 文章控制器
type ArticleController struct {
	db *gorm.DB
}

// NewArticleController 创建文章控制器
func NewArticleController(db *gorm.DB) *ArticleController {
	return &ArticleController{db: db}
}

// GetArticleList 获取文章列表
// @Summary 获取文章列表
// @Description 获取文章列表
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Param title query string false "文章标题"
// @Param categoryId query int false "分类ID"
// @Param status query int false "状态"
// @Success 200 {object} response.Response
// @Router /article/list [get]
func (ctrl *ArticleController) GetArticleList(c *gin.Context) {
	var req ArticleListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	// 构建查询条件
	query := ctrl.db.Model(&models.Article{})
	if req.Title != "" {
		query = query.Where("title LIKE ?", "%"+req.Title+"%")
	}
	if req.CategoryID != 0 {
		query = query.Where("category_id = ?", req.CategoryID)
	}
	if req.Status != 0 {
		query = query.Where("status = ?", req.Status)
	}

	// 获取总数
	var total int64
	query.Count(&total)

	// 分页查询
	var articles []models.Article
	offset := (req.Page - 1) * req.PageSize
	err := query.Preload("Category").Offset(offset).Limit(req.PageSize).Order("sort DESC, id DESC").Find(&articles).Error
	if err != nil {
		response.ServerError(c)
		return
	}

	// 构建响应数据
	var records []gin.H
	for _, article := range articles {
		record := gin.H{
			"id":         article.ID,
			"title":      article.Title,
			"categoryId": article.CategoryID,
			"category":   article.Category.Name,
			"image":      article.CoverImage,
			"summary":    article.Summary,
			"author":     article.Author,
			"sort":       article.Sort,
			"status":     article.Status,
			"createTime": article.CreateTime.Format("2006-01-02 15:04:05"),
			"updateTime": article.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		records = append(records, record)
	}

	response.PageSuccess(c, total, records, req.Page, req.PageSize)
}

// GetArticleDetail 获取文章详情
// @Summary 获取文章详情
// @Description 获取文章详情
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param id path int true "文章ID"
// @Success 200 {object} response.Response
// @Router /article/detail/{id} [get]
func (ctrl *ArticleController) GetArticleDetail(c *gin.Context) {
	id := utils.StringToUint64(c.Param("id"))
	if id == 0 {
		response.ParamError(c)
		return
	}

	// 查询文章
	var article models.Article
	if err := ctrl.db.Preload("Category").First(&article, id).Error; err != nil {
		response.NotFound(c)
		return
	}

	// 构建响应数据
	data := gin.H{
		"id":         article.ID,
		"title":      article.Title,
		"categoryId": article.CategoryID,
		"category":   article.Category.Name,
		"image":      article.CoverImage,
		"content":    article.Content,
		"summary":    article.Summary,
		"author":     article.Author,
		"sort":       article.Sort,
		"status":     article.Status,
		"createTime": article.CreateTime.Format("2006-01-02 15:04:05"),
		"updateTime": article.UpdateTime.Format("2006-01-02 15:04:05"),
	}

	response.Success(c, data)
}

// AddArticle 添加文章
// @Summary 添加文章
// @Description 添加文章
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body AddArticleRequest true "文章信息"
// @Success 200 {object} response.Response
// @Router /article/add [post]
func (ctrl *ArticleController) AddArticle(c *gin.Context) {
	var req AddArticleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 检查分类是否存在
	var category models.Category
	if err := ctrl.db.First(&category, req.CategoryID).Error; err != nil {
		response.Error(c, 400, "分类不存在")
		return
	}

	// 创建文章
	article := models.Article{
		Title:      req.Title,
		CategoryID: &req.CategoryID,
		CoverImage: req.Image,
		Content:    req.Content,
		Summary:    req.Summary,
		Author:     req.Author,
		Sort:       req.Sort,
		Status:     req.Status,
	}

	// 保存文章
	if err := ctrl.db.Create(&article).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// UpdateArticle 更新文章
// @Summary 更新文章
// @Description 更新文章
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body UpdateArticleRequest true "文章信息"
// @Success 200 {object} response.Response
// @Router /article/update [put]
func (ctrl *ArticleController) UpdateArticle(c *gin.Context) {
	var req UpdateArticleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 查询文章
	var article models.Article
	if err := ctrl.db.First(&article, req.ID).Error; err != nil {
		response.NotFound(c)
		return
	}

	// 检查分类是否存在
	var category models.Category
	if err := ctrl.db.First(&category, req.CategoryID).Error; err != nil {
		response.Error(c, 400, "分类不存在")
		return
	}

	// 更新文章信息
	article.Title = req.Title
	article.CategoryID = &req.CategoryID
	article.CoverImage = req.Image
	article.Content = req.Content
	article.Summary = req.Summary
	article.Author = req.Author
	article.Sort = req.Sort
	article.Status = req.Status

	// 保存文章
	if err := ctrl.db.Save(&article).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// DeleteArticle 删除文章
// @Summary 删除文章
// @Description 删除文章
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param id path int true "文章ID"
// @Success 200 {object} response.Response
// @Router /article/delete/{id} [delete]
func (ctrl *ArticleController) DeleteArticle(c *gin.Context) {
	id := utils.StringToUint(c.Param("id"))
	if id == 0 {
		response.ParamError(c)
		return
	}

	// 查询文章
	var article models.Article
	if err := ctrl.db.First(&article, id).Error; err != nil {
		response.NotFound(c)
		return
	}

	// 删除文章
	if err := ctrl.db.Delete(&article).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// CategoryListRequest 分类列表请求参数
type CategoryListRequest struct {
	Page     int    `form:"page"`
	PageSize int    `form:"pageSize"`
	Name     string `form:"name"`
	Status   int    `form:"status"`
}

// AddCategoryRequest 添加分类请求参数
type AddCategoryRequest struct {
	Name   string `json:"name" binding:"required"`
	Sort   int    `json:"sort"`
	Status int    `json:"status"`
}

// UpdateCategoryRequest 更新分类请求参数
type UpdateCategoryRequest struct {
	ID     uint   `json:"id" binding:"required"`
	Name   string `json:"name" binding:"required"`
	Sort   int    `json:"sort"`
	Status int    `json:"status"`
}

// GetCategoryList 获取分类列表
// @Summary 获取分类列表
// @Description 获取分类列表
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Param name query string false "分类名称"
// @Param status query int false "状态"
// @Success 200 {object} response.Response
// @Router /article/category/list [get]
func (ctrl *ArticleController) GetCategoryList(c *gin.Context) {
	var req CategoryListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	// 构建查询条件
	query := ctrl.db.Model(&models.Category{})
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Status != 0 {
		query = query.Where("status = ?", req.Status)
	}

	// 获取总数
	var total int64
	query.Count(&total)

	// 分页查询
	var categories []models.Category
	offset := (req.Page - 1) * req.PageSize
	err := query.Offset(offset).Limit(req.PageSize).Order("sort ASC, id ASC").Find(&categories).Error
	if err != nil {
		response.ServerError(c)
		return
	}

	// 构建响应数据
	var records []gin.H
	for _, category := range categories {
		record := gin.H{
			"id":         category.ID,
			"name":       category.Name,
			"sort":       category.Sort,
			"status":     category.Status,
			"createTime": category.CreateTime.Format("2006-01-02 15:04:05"),
			"updateTime": category.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		records = append(records, record)
	}

	response.PageSuccess(c, total, records, req.Page, req.PageSize)
}

// GetAllCategories 获取所有分类
// @Summary 获取所有分类
// @Description 获取所有分类
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} response.Response
// @Router /article/category/all [get]
func (ctrl *ArticleController) GetAllCategories(c *gin.Context) {
	var categories []models.Category
	if err := ctrl.db.Where("status = ?", 1).Order("sort ASC, id ASC").Find(&categories).Error; err != nil {
		response.ServerError(c)
		return
	}

	// 构建响应数据
	var records []gin.H
	for _, category := range categories {
		record := gin.H{
			"id":   category.ID,
			"name": category.Name,
		}
		records = append(records, record)
	}

	response.Success(c, records)
}

// AddCategory 添加分类
// @Summary 添加分类
// @Description 添加分类
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body AddCategoryRequest true "分类信息"
// @Success 200 {object} response.Response
// @Router /article/category/add [post]
func (ctrl *ArticleController) AddCategory(c *gin.Context) {
	var req AddCategoryRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 检查分类名称是否已存在
	var count int64
	if err := ctrl.db.Model(&models.Category{}).Where("name = ?", req.Name).Count(&count).Error; err != nil {
		response.ServerError(c)
		return
	}
	if count > 0 {
		response.Error(c, 400, "分类名称已存在")
		return
	}

	// 创建分类
	category := models.Category{
		Name:   req.Name,
		Sort:   req.Sort,
		Status: req.Status,
	}

	// 保存分类
	if err := ctrl.db.Create(&category).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// UpdateCategory 更新分类
// @Summary 更新分类
// @Description 更新分类
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body UpdateCategoryRequest true "分类信息"
// @Success 200 {object} response.Response
// @Router /article/category/update [put]
func (ctrl *ArticleController) UpdateCategory(c *gin.Context) {
	var req UpdateCategoryRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 查询分类
	var category models.Category
	if err := ctrl.db.First(&category, req.ID).Error; err != nil {
		response.NotFound(c)
		return
	}

	// 检查分类名称是否已存在（排除自己）
	var count int64
	if err := ctrl.db.Model(&models.Category{}).Where("name = ? AND id != ?", req.Name, req.ID).Count(&count).Error; err != nil {
		response.ServerError(c)
		return
	}
	if count > 0 {
		response.Error(c, 400, "分类名称已存在")
		return
	}

	// 更新分类信息
	category.Name = req.Name
	category.Sort = req.Sort
	category.Status = req.Status

	// 保存分类
	if err := ctrl.db.Save(&category).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// DeleteCategory 删除分类
// @Summary 删除分类
// @Description 删除分类
// @Tags 文章管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param id path int true "分类ID"
// @Success 200 {object} response.Response
// @Router /article/category/delete/{id} [delete]
func (ctrl *ArticleController) DeleteCategory(c *gin.Context) {
	id := utils.StringToUint(c.Param("id"))
	if id == 0 {
		response.ParamError(c)
		return
	}

	// 查询分类
	var category models.Category
	if err := ctrl.db.First(&category, id).Error; err != nil {
		response.NotFound(c)
		return
	}

	// 检查分类下是否有文章
	var count int64
	if err := ctrl.db.Model(&models.Article{}).Where("category_id = ?", id).Count(&count).Error; err != nil {
		response.ServerError(c)
		return
	}
	if count > 0 {
		response.Error(c, 400, "请先删除分类下的文章")
		return
	}

	// 删除分类
	if err := ctrl.db.Delete(&category).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}